package datos.clases;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import tipos.clases.Donacion;
import tipos.clases.Ong;

import datos.interfaces.IDonacionesDAO;

public class JDBCDonacionesDAO implements IDonacionesDAO{
	
	public List select(){
		Connection c = ConnectionManager.getInstance().checkOut();
		List res = new LinkedList();
		PreparedStatement stmt = null;
        ResultSet result = null;        
        String sql = "SELECT * FROM Ong_Catastrofe";
        
        try{
        	if(c==null){
        		System.out.println("No hay conexion");
        	}
        	stmt = c.prepareStatement(sql);      
        	stmt.executeQuery(sql);
            result = stmt.executeQuery();    
            while (result.next()) {
                Donacion temp = new Donacion();             
                temp.setIDOng(result.getInt("Id_o"));
                temp.setIDCatastrofe(result.getInt("Id_c"));     
                temp.setCantidad(result.getInt("cantidad"));     
                res.add(temp);
            }
            
        }catch(SQLException e){
        	e.printStackTrace();
        }finally{
        	  try {
                  if (result != null) {
                      result.close();
                  }
                  if (stmt != null) {
                      stmt.close();
                  }
              } catch (SQLException e) {
              }
        }
		return res;
	}

	
	public void insertaDonacion(Donacion d) {
		Connection c = ConnectionManager.getInstance().checkOut();		
		PreparedStatement stmt = null;
            
        String sql = "UPDATE ong_catastrofe SET cantidad=cantidad + ? WHERE(id_o = ? && id_c = ?)";	
        
        try {
        	
            stmt = c.prepareStatement(sql);
            stmt.setInt(1, d.getCantidad());
            stmt.setInt(2, d.getIDOng());
            stmt.setInt(3, d.getIDCatastrofe());            
            stmt.executeUpdate();

        } catch (SQLException e) {
            System.out.println("Message: " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("ErrorCode: " + e.getErrorCode());
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
            }
        }
        
	}

}
